<script setup lang="ts">
import { URL_CATEGROIES } from '@/data/constants';
import { useHomeTitle } from '@/events/title'
import { Sort } from '@/ts/interfaces/sort.interfaces';
import { Ref, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';

const { t } = useI18n()

//Title
useHomeTitle(t('category.name', 2))

const loaded = ref(false)
const errMsg: Ref<string | null> = ref(null)

//Apps
const apps = ref<Sort[] | null>(null)
onMounted(() => {
  fetch(URL_CATEGROIES)
    .then(response => response.json())
    .then(data => {
      // console.log(data)
      if (data.state === 200) {
        apps.value = data.data
      }
    })
    .catch((reason) => {
      console.error('Can\'t load data:', reason)
      errMsg.value = reason.toString()
    })
    .finally(() => {
      loaded.value = true
    })
})


</script>

<template>
  <v-container class="py-0">
    <!-- Alerts -->
    <v-alert class="my-4" v-if="errMsg" title="Load error" :text="errMsg" type="error" variant="tonal" />
  </v-container>
  <v-container class="py-0">
    <!-- 应用分类 -->
    <v-list v-for="group in apps" :key="group.name" class="my-4" border rounded="lg">
      <v-list-subheader>{{ group.name }}</v-list-subheader>
      <v-row v-if="group.prjInfoList" class="projectGroup" no-gutters>
        <!-- TODO:使用应用id作为key -->
        <!--  eslint-disable-next-line vue/valid-v-for -->
        <v-col v-for="(item, index) in group.prjInfoList" :key="index" cols="3" sm="2" lg="1">
          <v-list-item class="projectItem rounded" :to="`/app/${item.prjId}/android/${item.platforms.android[0]}`">
            <v-img :src="item.iconUrl" class="icon elevation-1 rounded-lg" />
            <div class="appName">{{ item.name }}</div>
          </v-list-item>
        </v-col>
      </v-row>
    </v-list>
  </v-container>
  <!-- Loading -->
  <div v-if="!loaded" class="centerSpace">
    <v-progress-circular indeterminate :size="40" :width="4" />
  </div>
</template>

<style scoped lang="scss">
.projectGroup {
  padding: 0 8px;
}

.projectItem {
  padding: 8px;
  display: block;
  overflow: visible;

  :deep(.v-list-item__content) {
    overflow: visible;

    .icon {
      width: 100%;
      aspect-ratio: 1;
    }

    .appName {
      text-align: center;
      font-size: .875rem;
    }
  }
}
</style>
